<template>
    <!-- 算法服务化发布在线开发调试 -->
    <div class="model-manage">
        <div class="mm-panel-wrapper-left">
            <Tree ref="leftTreeRef" :isOwnAccount="true" :topAdd="true" :topAddMenu="right_menuList.rightMenuList_1"
                :folderMenu="right_menuList.rightMenuList_3" :fileMenu="right_menuList.rightMenuList_4"
                :treeData="ownTreeData" :currentNodeKey="currentNodeKey" :defaultExpandedKeys="defaultExpandedKeys"
                @handleAddNode="handleAddModel" @addOrUpdateFolder="handleAddOrUpdateFolder" @nodeClick="nodeClick"
                @nodeDelete="handleNodeDelete" @moveNodeOrder="moveNodeOrder" @handleMenuClick="handleMenuClick">
            </Tree>
        </div>
        <div class="mm-divider"></div>
        <div class="mm-panel-wrapper-right">
            <div class="padding20">
                <div class="mm-panel-title">
                    <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery"
                        @clear="handleQuery" @change="handleQuery" class="w-full" style="width:200px;"></el-input>
                    <el-button class="ml-10" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button class="ml-10" type="primary" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                    <el-button class="ml-10" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
                </div>
                <!-- @selection-change="handleSelectionChange" -->
                <el-table v-loading="loading" :data="tableList">
                    <!-- <el-table-column type="selection" align="center" width="55"></el-table-column> -->
                    <el-table-column label="序号" type="index" width="50" align="center">
                        <template slot-scope="scope">
                            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true" width="200" />
                    <el-table-column label="样本大小（M）" align="center" prop="size" :show-overflow-tooltip="true"
                        width="120" />
                    <el-table-column label="样本数量" align="center" prop="count" :show-overflow-tooltip="true"
                        width="120" />
                    <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
                    <el-table-column label="质量评估结果" align="center" prop="qualityResult" :show-overflow-tooltip="true"
                        width="200" />
                    <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
                    <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-dropdown @command="handleCommand">
                                <el-button type="primary">
                                    <i class="el-icon-more"></i>
                                </el-button>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item command="1">详情</el-dropdown-item>
                                    <el-dropdown-item command="2">编辑</el-dropdown-item>
                                    <el-dropdown-item command="3">删除</el-dropdown-item>
                                    <el-dropdown-item command="4">下载</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <el-dialog title="新增" :visible.sync="openDialog" width="800px" append-to-body>
            <div></div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary">确 定</el-button>
                <el-button @click="openDialog = false">取 消</el-button>
            </div>
        </el-dialog>
        <AddOrUpdateFolder v-if="isAddOrUpdateFolder" ref="addOrUpdateFolderRef" @refresh="getList"></AddOrUpdateFolder>
        <AddOrUpdateModel v-if="isAddOrUpdateModel" ref="addOrUpdateModelRef" @refresh="getList"></AddOrUpdateModel>
    </div>
</template>

<script>
import { mapState } from "vuex";
import {
    addModel,
    deleModel,
    getSelfModelTree,
    moveTreeNodeOrder,
} from "@/api/myspace/model-manage-tool/model-manage";
import Tree from "@/components/LeftTree/tree.vue";
import AddOrUpdateModel from "./components/add-or-update-model.vue";
import AddOrUpdateFolder from "./components/add-or-update-folder.vue";

export default {
    data() {
        return {
            openDialog: false,
            loading: false,
            tableList: [
                {
                    name: "xxxxx",
                    size: 300,
                    count: 10000,
                    description: "针对xxx生成的样本数据",
                    qualityResult: "完整性80%，多样性60%",
                    createTime: "2021-01-01 10:10:10",
                }
            ],
            queryParams: { // 查询参数
                pageNum: 1,
                pageSize: 10,
                name: "",
                modelId: "",
                folderId: "",
            },
            isAddOrUpdateModel: false, // 是否打开新增数据模型弹框
            isAddOrUpdateFolder: false, // 是否打开创建目录的弹框
            isFolder: false, // 是否展示文件夹详情
            isFile: false, // 是否展示文件详情
            isModel: false, //是否是模型详情
            isModelGroupDetail: false, // 是否展示模型组详情,
            selectedNodeInfo: {}, // 当前选中节点的信息
            ownTreeData: [], // 本账户模型列表
            currentNodeKey: 0, // 当前选中节点的key
            defaultExpandedKeys: [] // 默认展开的节点
        };
    },
    components: {
        Tree,
        AddOrUpdateModel,
        AddOrUpdateFolder,
    },
    computed: {
        ...mapState({
            right_menuList: (state) => state.modelManageTool.right_menuList,
            selectedNodeId: (state) => state.modelManageTool.model.selectedNodeId,
            expandedNodeIds: (state) => state.modelManageTool.model.expandedNodeIds,
        }),
    },
    async created() {
        await this.getList();
        this.currentNodeKey = this.selectedNodeId;
        this.defaultExpandedKeys = this.expandedNodeIds;
        this.$nextTick(() => {
            this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
        })
    },
    mounted() {

    },
    methods: {
        handleCommand(command) {
            this.$message('click on item ' + command);
        },
        //新增
        handleAdd() {
            this.openDialog = true;
        },
        //查询
        handleQuery() {

        },
        //重置搜索条件
        resetQuery() {

        },
        async getList(newNodeId) {
            await getSelfModelTree().then((res) => {
                if (res.code == 200 && Array.isArray(res.data)) {
                    this.ownTreeData = res.data[0].commonTreeList;
                    // this.nodeClick(
                    //   newNodeId ? this.recurNodeForTarget(this.ownTreeData, newNodeId) :
                    //     this.selectedNodeId ? this.recurNodeForTarget(this.ownTreeData, this.selectedNodeId) :
                    //       this.ownTreeData[0])

                    const targetId = newNodeId || this.selectedNodeId;
                    const targetnode = targetId ? this.recurNodeForTarget(this.ownTreeData, targetId) : this.ownTreeData[0];
                    this.nodeClick(targetnode);
                }
            });
        },
        // 递归获取当前树节点
        recurNodeForTarget(nodeArr, id) {
            for (let i = 0; i < nodeArr.length; i++) {
                if (nodeArr[i].id == id) {
                    return nodeArr[i];
                } else {
                    if (nodeArr[i].children && nodeArr[i].children.length > 0) {
                        let node = this.recurNodeForTarget(nodeArr[i].children, id);
                        if (node) {
                            return node;
                        }
                    }
                }
            }
        },
        // 新增文件夹
        handleAddOrUpdateFolder(sign, node) {
            this.isAddOrUpdateFolder = true;
            this.$nextTick(() => {
                this.$refs["addOrUpdateFolderRef"].init(
                    sign,
                    node,
                    this.ownTreeData,
                    "account"
                );
            });
        },
        // 新增数据模型
        handleAddModel(node) {
            this.isAddOrUpdateModel = true;
            this.$nextTick(() => {
                this.$refs["addOrUpdateModelRef"].init(undefined, node);
            });
        },
        // 点击树节点，右侧展示详细信息
        nodeClick(node) {
            if (node == undefined) {
                return;
            }
            this.selectedNodeInfo = node;
            this.currentNodeKey = node.id;
            this.$nextTick(() => {
                this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
            })
            this.$store.commit("modelManageTool/SET_SELECTED_NODE_ID", { moduleName: 'model', id: node.id })
            if (!node.data) return;

            if (node.type == 0) {
                // 点击的文件夹
                this.isFolder = true;
                this.isModel = false;
                this.$store.commit("modelManageTool/SET_EXPANDED_NODE_IDS", { moduleName: 'model', idList: Array.from(new Set([...this.defaultExpandedKeys, node.id])) })
            } else {
                // 点击的文件
                this.isFolder = false;
                this.isFile = true;
                this.isModel = true;
            }
        },
        /**
         * 树节点删除事件的回调
         * @param node 被删除的节点
         */
        handleNodeDelete(node) {
            this.$confirm(
                `确定删除${node.type == 0 ? "目录" : "数据模型"}  ${node.data.modelName
                } ?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    customClass: "message-box-style",
                    type: "warning",
                }
            )
                .then(() => {
                    deleModel(node.id).then((response) => {
                        console.log(response);
                        if (response.code == 200) {
                            this.$message.success(
                                this.$toolHandle.getI18nName(
                                    this.$zh.setup.responseText,
                                    this.$en.setup.responseText,
                                    this.$i18n.locale,
                                    "success"
                                )
                            );
                            if (node.id == this.currentNodeKey) {
                                this.isFolder = false;
                                this.isModel = false;
                            }
                            this.getList();
                        }
                    });
                })
                .catch(() => { });
        },
        /**
         * 树节点复制事件的回调
         * @param node 被复制的节点
         */
        handleCopyFile(node) {
            addModel({
                modelName: node.data.modelName + " Copy",
                modelEnglishName: node.data.modelEnglishName + " Copy",
                modelAlias: node.data.modelAlias + " Copy",
                parentId: node.data.parentId,
                nodeType: node.type, // 0表示文件夹，1表示文件
                categoryLabel: node.data.categoryLabel,
                modelResolution: node.data.modelResolution,
                modelDescription: node.data.modelDescription,
                modelType: node.data.modelType, // 0表示标准模型，1表示代理模型，2表示数字样机
                userId: node.data.userId,
            }).then((response) => {
                if (response.code == 200) {
                    this.$message.success(
                        this.$toolHandle.getI18nName(
                            this.$zh.setup.responseText,
                            this.$en.setup.responseText,
                            this.$i18n.locale,
                            "success"
                        )
                    );
                    this.getList();
                }
            });
        },
        // 移动树节点的顺序
        moveNodeOrder(draggingNode, dropNode, dropType) {
            moveTreeNodeOrder({
                movedNodeId: draggingNode.data.id, // 被移动节点的id
                referenceNodeId: dropNode.data.id, // 参照节点的id
                position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
                ancestors: draggingNode.data.data.ancestors, // 祖先
                folderChildrenOrder: {
                    parentId:
                        dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
                    siblingIds:
                        dropType == "inner"
                            ? Array.from(dropNode.childNodes).map((item) => item.data.id)
                            : Array.from(dropNode.parent.childNodes).map(
                                (item) => item.data.id
                            ),
                },
            }).then((response) => {
                if (response.code == 200) {
                    this.$message.success(
                        this.$toolHandle.getI18nName(
                            this.$zh.setup.responseText,
                            this.$en.setup.responseText,
                            this.$i18n.locale,
                            "success"
                        )
                    );
                    this.getList();
                }
            });
        },
        // 点击菜单项触发的事件
        handleMenuClick(menu, node) {
            switch (menu.name) {
                case "新增数据模型":
                case "新增装备模型":
                    this.handleAddModel(node);
                    break;
                case "新增分类":
                    this.handleAddOrUpdateFolder("add");
                    break;
                case "添加子目录":
                    this.handleAddOrUpdateFolder("add", node);
                    break;
                case "编辑":
                    this.handleAddOrUpdateFolder("edit", node);
                    break;
                case "复制":
                    // 文件的复制
                    this.handleCopyFile(node);
                    break;
                case "删除":
                    // 文件夹/文件的删除
                    this.handleNodeDelete(node);
                    break;
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.model-manage {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;

    .mm-panel-wrapper-left {
        width: 300px;
        height: 100%;
        flex-grow: 0;
        flex-shrink: 0;
        display: flex;
        position: relative;
        padding: 0 10px;
    }

    .mm-divider {
        width: 1px;
        height: auto;
        flex-grow: 0;
        position: relative;
        align-self: stretch;
        background-color: var(--ui-border-color-split);
    }

    .mm-panel-wrapper-right {
        width: 256px;
        height: 100%;
        min-width: 0px;
        flex-grow: 1;
        flex-shrink: 1;
        display: flex;
        position: relative;
        overflow: auto;
    }
}

.padding20 {
    padding: 20px;
    width: 100%;
}
</style>